const { sys_dict_model:SysDictModel, sys_dict_data_model:SysDictDataModel } = require('../models');
const { Op } = require('sequelize');
const DateUtils = require('../utils/dateUtils');
const { realDelete } = require('../config/system');

// 获取字典数据分页列表
async function getDictDataPage(pageNum, pageSize, dictCode, status, keywords) {
    const offset = (pageNum - 1) * pageSize;
    const where = {
        dictCode: dictCode,
    };
    if (status !== undefined) {
        where.status = status;
    }
    if (keywords) {
        where.label = {
            [Op.like]: `%${keywords}%`
        };
    }
    return await SysDictDataModel.findAndCountAll({
        where,
        order: [['sort', 'ASC']],
        limit: pageSize,
        offset
    });
}

// 获取字典数据列表
async function getDictDataList(dictCode, status, label) {
    const where = {};
    if (dictCode) {
        where.dict_code = dictCode;
    }
    if (status !== undefined) {
        where.status = status;
    }
    if (label) {
        where.label = {
            [Op.like]: `%${label}%`
        };
    }
    return await SysDictDataModel.findAll({
        where,
        order: [['sort', 'ASC']]
    });
}

// 根据ID获取字典数据详情
async function getDictDataById(id) {
    const dictData = await SysDictDataModel.findByPk(id);
    if (!dictData) {
        throw new Error('字典数据不存在');
    }
    return dictData;
}

// 新增字典数据
async function createDictData(dictData) {
    // 校验字典编码是否存在
    const dict = await SysDictModel.findOne({
        where: { dictCode: dictData.dictCode }
    });
    if (!dict) {
        throw new Error('字典类型不存在');
    }

    // 创建字典数据
    return await SysDictDataModel.create({
        ...dictData,
        create_time: DateUtils.getCurrentTime()
    });
}

// 更新字典数据
async function updateDictData(id, dictData) {
    const existingDictData = await SysDictDataModel.findByPk(id);
    if (!existingDictData) {
        throw new Error('字典数据不存在');
    }

    // 如果更新了字典编码，需要校验字典类型是否存在
    if (dictData.dictCode && dictData.dictCode !== existingDictData.dictCode) {
        const dict = await SysDictModel.findOne({
            where: { dict_code: dictData.dictCode }
        });
        if (!dict) {
            throw new Error('字典类型不存在');
        }
    }

    // 更新字典数据
    await existingDictData.update({
        ...dictData,
        update_time: DateUtils.getCurrentTime()
    });

    return existingDictData;
}

// 删除字典数据
async function deleteDictData(id) {
    const dictData = await SysDictDataModel.findByPk(id);
    if (!dictData) {
        throw new Error('字典数据不存在');
    }
    if (realDelete) {
        // 真实删除
        await dictData.destroy();
    } else {
        // 软删除
        await dictData.update({
            is_deleted: 1,
            update_time: DateUtils.getCurrentTime()
        });
    }
}

module.exports = {
    getDictDataPage,
    getDictDataList,
    getDictDataById,
    createDictData,
    updateDictData,
    deleteDictData
};